package pro.cherish.knowledgedemothymeleaf.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.jhonnymertz.wkhtmltopdf.wrapper.configurations.WrapperConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.ByteUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.Context;
import org.thymeleaf.dialect.IDialect;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.dialect.SpringStandardDialect;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.StringTemplateResolver;
import pro.cherish.knowledgedemothymeleaf.core.HtmlToPdf;
import pro.cherish.knowledgedemothymeleaf.core.WkHtmlToPdfUtil;
import pro.cherish.knowledgedemothymeleaf.entity.ProjectInfo;
import pro.cherish.knowledgedemothymeleaf.entity.Qs;
import pro.cherish.knowledgedemothymeleaf.entity.UserEntity;
import pro.cherish.knowledgeutil.json.JsonUtilExt;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 创建人：cherish
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2020-02-07 cherish 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：TemplateController
 * @Description 功能说明：将模板文件转为html再将html转为pdf
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2020-02-07 cherish
 */
@Controller
@Slf4j
public class TemplateController {

    @GetMapping("demmand")
    public String showDemand(ModelMap map) {
        ArrayList<Qs> qsList = new ArrayList<>();
        qsList.add(new Qs("专家", 1));
        qsList.add(new Qs("供应", 2));
        ProjectInfo projectinfo = ProjectInfo.builder()
                .purchaserOrgName("A单位")
                .planRecordCode("111")
                .projectName("A项目")
                .projectTypeName("货物")
                .budget(BigDecimal.valueOf(200))
                .purchaseMethodName("单一来源")
                .expertNumberList(qsList)
                .purchaserLinkTel("17720799637")
                .purchaserLinkName("cherish")
                .bidConfirmMethod("A确认发那个谁")
                .build();
        String s = JsonUtilExt.toJsonString(projectinfo);
        log.info("【数据】{}", s);
        map.put("projectInfo", projectinfo);
        return "test";
    }

    @GetMapping("demandToPdf")
    public void demandToPdf(HttpServletResponse response) throws IOException {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("templates/test.html");
        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8.name());
        String content = writer.toString();
        log.info("模板内容{}", content);
        ArrayList<Qs> qsList = new ArrayList<>();
        qsList.add(new Qs("专家", 1));
        qsList.add(new Qs("供应", 2));
        ProjectInfo projectinfo = ProjectInfo.builder()
                .purchaserOrgName("A单位")
                .planRecordCode("111")
                .projectName("A项目")
                .projectTypeName("货物")
                .budget(BigDecimal.valueOf(200))
                .purchaseMethodName("单一来源")
                .expertNumberList(qsList)
                .purchaserLinkTel("17720799637")
                .purchaserLinkName("cherish")
                .bidConfirmMethod("A确认发那个谁")
                .build();
        String s = JsonUtilExt.toJsonString(projectinfo);
        log.info("【数据】{}", s);
        Map<String, Object> map = new HashMap<>();
        map.put("projectInfo", projectinfo);
        // 构造上下文(Model)
        Context context = new Context();
        context.setVariables(map);
        // 渲染模板
        // 构造模板引擎
        SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
        IDialect springStandarDialect = new SpringStandardDialect();
        springTemplateEngine.setDialect(springStandarDialect);
        StringTemplateResolver stringTemplateResolver = new StringTemplateResolver();
        stringTemplateResolver.setCacheable(false);
        stringTemplateResolver.setTemplateMode(TemplateMode.HTML);
        springTemplateEngine.setTemplateResolver(stringTemplateResolver);
        String str = springTemplateEngine.process(content, context);
        log.info("【最后渲染的结果】{}", str);
        // 下载相关设置
        String fileName = "result.pdf";
        // 设置强制下载不打开
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + ";charset=utf-8");
        // 设置文件名
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8"));
        byte[] bytes = html2Pdf(str);
        InputStream is = new ByteArrayInputStream(bytes);
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is,os);
    }
    /**
     *
     * @Title: downloadFile
     * @Description: 单文件下载
     * @return
     * @return RestResponse<byte[]>
     */
    @GetMapping("/download")
    public void downloadFile(
           @RequestParam(name ="path",required = true) String path,
          @RequestParam(name ="fileName",required = true) String fileName
            , HttpServletResponse response) {
        try {
            path=new String(path.getBytes("iso8859-1"),"UTF-8");
            fileName= new String(fileName.getBytes("iso8859-1"),"UTF-8");
            // 下载路径
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            byte[] fileByte = new byte[20];
            if (ObjectUtil.isNotNull(fileByte)){
                response.getOutputStream().write(fileByte);
            }else{
                throw new RuntimeException();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * wkhtmltopdf命令，linux默认地址为：/usr/local/bin/wkhtmltopdf
     */
    @Value("${wkhtmltopdf.command:D:\\mytool\\wkhtmltopdf\\bin\\wkhtmltopdf.exe}")
    String wkhtmltopdfCommand;

    public byte[] html2Pdf(String content) throws FileNotFoundException {
        File htmlFile = new File("D:\\temp\\haha\\hi.html");
        File pdfFile = new File("D:\\temp\\haha\\hi.pdf");
        FileOutputStream stream = new FileOutputStream(htmlFile);
        byte[] bytes = StrUtil.bytes(content);
        IoUtil.write(stream,false,bytes);
        boolean convert = HtmlToPdf.convert(htmlFile.getAbsolutePath(), pdfFile.getAbsolutePath());
        if(convert){
            return IoUtil.readBytes(new FileInputStream("D:\\temp\\haha\\hi.pdf"));
        }else{
            log.error("转换失败");
            return null;
        }
    }


    @GetMapping("render")
    public String show(ModelMap map) {
        map.put("thText", "设置文本内容");
        map.put("thUText", "设置文本内容");
        map.put("thValue", "设置当前元素的value值");
        map.put("thEach", Arrays.asList("元素一", "元素二"));
        map.put("thIf", "msg is not null");
        map.put("thObject", new UserEntity("123", "lys", "admin"));
        return "test";
    }

    @ResponseBody
    @GetMapping("getHtml")
    public String getHtmlContent() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("templates/test.html");
        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8.name());
        String content = writer.toString();
        log.info("文件内容", content);
        Map<String, Object> map = new HashMap<>();
        map.put("thText", "设置文本内容");
        map.put("thUText", "设置文本内容");
        map.put("thValue", "设置当前元素的value值");
        map.put("thEach", Arrays.asList("列表", "遍历列表"));
        map.put("thIf", "msg is not null");
        map.put("thObject", new UserEntity("123", "lys", "admin"));
        // 构造上下文(Model)
        Context context = new Context();
        context.setVariables(map);
        // 渲染模板
        // 构造模板引擎
        SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
        IDialect springStandarDialect = new SpringStandardDialect();
        springTemplateEngine.setDialect(springStandarDialect);
        StringTemplateResolver stringTemplateResolver = new StringTemplateResolver();
        stringTemplateResolver.setCacheable(false);
        stringTemplateResolver.setTemplateMode(TemplateMode.HTML);
        springTemplateEngine.setTemplateResolver(stringTemplateResolver);
        String str = springTemplateEngine.process(content, context);
        return str;
    }


}
